package android.slc.mp.ui.page;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.slc.ma.MaBaseAdapter;
import android.slc.mp.R;
import android.slc.mp.SlcMp;
import android.slc.mp.po.i.IBaseFolder;
import android.slc.mp.po.i.IBaseItem;
import android.slc.mp.po.i.IBaseResult;
import android.slc.mp.ui.SlcIMpDelegate;
import android.slc.mp.ui.page.audio.SlcMpPagerAudioFragment;
import android.slc.mp.ui.page.file.SlcMpPagerFileFragment;
import android.slc.mp.ui.page.photo.SlcMpPagerPhotoFragment;
import android.slc.mp.ui.page.video.SlcMpPagerVideoFragment;
import android.slc.mp.ui.widget.SlcMpMaxHeightRecyclerView;
import android.slc.popup.SlcPopup2;
import android.slc.popup.fast.ShadowPopupWindow;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * Created by slc
 * A placeholder fragment containing a simple view.
 */
public abstract class SlcMpPagerBaseFragment<S extends IBaseResult<F, T>, F extends IBaseFolder<T>,
        T extends IBaseItem> extends Fragment implements
        SlcIMpFragmentView<S, F, T>, SlcMpPagerVirtualVm.OnResultListener<List<T>>, View.OnClickListener {
    public final static String POSITION = "position";
    private View mContentView;
    protected SlcMpPagerVirtualVm<S, F, T> mMpVirtualVm;

    //列表
    protected RecyclerView mediaPickerRecyclerView;
    protected SlcMpBaseMpAdapter<T> adapter;

    public static SlcMpPagerBaseFragment<?, ?, ?> newInstance(int mediaType, SlcIMpDelegate slcIMpDelegate) {
        return newInstance(0, mediaType, slcIMpDelegate);
    }

    public static SlcMpPagerBaseFragment<?, ?, ?> newInstance(int position, int mediaType,
                                                              SlcIMpDelegate slcIMpDelegate) {
        SlcMpPagerBaseFragment<?, ?, ?> fragment;
        switch (mediaType) {
            case SlcMp.MEDIA_TYPE_PHOTO:
                fragment = new SlcMpPagerPhotoFragment();
                break;
            case SlcMp.MEDIA_TYPE_VIDEO:
                fragment = new SlcMpPagerVideoFragment();
                break;
            case SlcMp.MEDIA_TYPE_AUDIO:
                fragment = new SlcMpPagerAudioFragment();
                break;
            //case SlcMp.MEDIA_TYPE_FILE:
            default:
                fragment = new SlcMpPagerFileFragment();
                break;
        }
        //此j句暂时用不到
        /*if (fragment == null) {
            throw new IllegalStateException("媒体类型异常，请参考MediaPicker中的媒体类型");
        }*/
        fragment.setMediaPickerDelegate(mediaType, slcIMpDelegate);
        Bundle bundle = new Bundle();
        bundle.putInt(SlcMp.Key.KEY_MEDIA_TYPE, mediaType);
        bundle.putInt(POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 设置代理器
     *
     * @param mediaType
     * @param slcIMpDelegate
     */
    public void setMediaPickerDelegate(int mediaType, SlcIMpDelegate slcIMpDelegate) {
        this.mMpVirtualVm = getMediaPickerListDelegate(mediaType, slcIMpDelegate);
    }

    ///////////////  初始化 start  ////////////////

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (!(context instanceof FragmentActivity)) {
            //必须实现自FragmentActivity
            throw new RuntimeException(context.getClass().getSimpleName() + " must impl FragmentActivity!");
        }
    }

    public <V extends View> V findViewById(@IdRes int id) {
        return mContentView.findViewById(id);
    }

    @LayoutRes
    protected abstract int getContentView();

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mContentView = inflater.inflate(getContentView(), container, false);
        slcMtBindView(savedInstanceState);
        slcMtInitData();
        return mContentView;
    }

    @Override
    public void slcMtBindView(@Nullable Bundle savedInstanceState) {
        mediaPickerRecyclerView = findViewById(getMediaPickerViewId());
        mediaPickerRecyclerView.setLayoutManager(getMediaPickerRecyclerViewLayoutManager());
    }

    @Override
    public void slcMtInitData() {
        mMpVirtualVm.setOnDataRefreshListener(this);
        mMpVirtualVm.loader(getActivity());
    }

    @IdRes
    protected abstract int getMediaPickerViewId();

    /**
     * 获取列表管理器
     *
     * @return
     */
    protected RecyclerView.LayoutManager getMediaPickerRecyclerViewLayoutManager() {
        return new GridLayoutManager(getContext(),
                mMpVirtualVm.getMediaPickerDelegate().getSpanCount());
    }

    protected abstract SlcMpBaseMpAdapter<T> getMediaPickerAdapter(List<T> data);

    /**
     * 刷新媒体列表
     *
     * @param data
     */
    protected void refreshMediaListView(List<T> data) {
        if (adapter == null) {
            adapter = getMediaPickerAdapter(data);
            adapter.setOnItemClickListener(new MaBaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(MaBaseAdapter<?> adapter, View view, int position) {
                    SlcMpPagerBaseFragment.this.onItemClick(adapter, view, position);
                }
            });
            adapter.setOnItemChildClickListener(new MaBaseAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(MaBaseAdapter<?> adapter, View view, int position) {
                    SlcMpPagerBaseFragment.this.onItemChildClick(adapter, view, position);
                }
            });
            mediaPickerRecyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    protected void refreshFolderInfo() {
        F allItemFolder = mMpVirtualVm.getResult().getAllItemFolder();
        //此处代码有问题
        setSelectFolderName(allItemFolder == null ? null : mMpVirtualVm.getResult().getAllItemFolder().getName());
    }

    /**
     * 点击事件
     *
     * @param adapter
     * @param view
     * @param position
     */
    protected void onItemClick(MaBaseAdapter<?> adapter, View view, int position) {
        //此处暂时注销
        //mMpVirtualVm.onItemClick(position);
    }

    /**
     * 子item点击事件
     *
     * @param adapter
     * @param view
     * @param position
     */
    protected void onItemChildClick(MaBaseAdapter<?> adapter, View view, int position) {
        if (view.getId() == R.id.checkbox) {
            CheckBox checkBox = (CheckBox) view;
            checkBox.setChecked(!checkBox.isChecked());
            mMpVirtualVm.selectItem(position);
        } else {
            mMpVirtualVm.onItemChildClick(position);
        }
    }

    /**
     * 选择事件
     *
     * @param position
     * @param baseItem
     */
    protected void onCheck(int position, IBaseItem baseItem) {
        SlcMpPagerBaseFragment.this.adapter.notifyDataSwitch(position);
    }

    @Override
    public void onLoadResult(List<T> data) {
        refreshMediaListView(data);
        refreshFolderInfo();
    }

    ////////切换文件夹相关对话框和事件////////
    protected void showSwitchFolderDialog(View anchor) {
        SlcMpMaxHeightRecyclerView recyclerView = new SlcMpMaxHeightRecyclerView(getContext());
        int heightPixels = getResources().getDisplayMetrics().heightPixels;
        recyclerView.setMaxHeight((int) (heightPixels - heightPixels / 3f));
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        MaBaseAdapter<?> slcBaseAdapter = getSwitchFolderAdapter();
        slcBaseAdapter.setOnItemClickListener(new MaBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(MaBaseAdapter<?> adapter, View view, int position) {
                SlcPopup2.dismissByKey(String.valueOf(SlcMpPagerBaseFragment.this.hashCode()));
                onSwitchFolderDialogItemClick(position);
            }
        });
        recyclerView.setAdapter(slcBaseAdapter);
        SlcPopup2.createShadowPopupOperate()
                .setKey(String.valueOf(hashCode()))
                .show(new ShadowPopupWindow(requireContext())
                        .setContentView(recyclerView)
                        .setAnchor(anchor)
                        .setCancelable(true)
                        .setBgDrawable(new ColorDrawable(Color.WHITE)).create());
    }

    protected MaBaseAdapter<?> getSwitchFolderAdapter() {
        return new SlcMpFolderAdapter<>(requireContext(), mMpVirtualVm.getResult().getFolders());
    }

    protected void onSwitchFolderDialogItemClick(int position) {
        F baseFolder = mMpVirtualVm.getResult().getFolders().get(position);
        setSelectFolderName(baseFolder.getName());
        mMpVirtualVm.setCurrentMediaList(baseFolder.getItems());
        adapter.notifyDataSetChanged();
    }

    /**
     * 设置文件夹名名称
     *
     * @param folderName
     */
    protected abstract void setSelectFolderName(String folderName);


    @Override
    public void onDestroyView() {
        mMpVirtualVm.setOnDataRefreshListener(null);
        SlcPopup2.dismissByKey(String.valueOf(SlcMpPagerBaseFragment.this.hashCode()));
        super.onDestroyView();
    }
}